<?php
require_once ('ini_set.inc');
require_once ('LyException.php');
require_once ('db.php');
require_once ('ClassUtil.php');
require_once ('Category.php');
class CategoryManage {
	
	public $category = array();
	public function add_category(Category $categrory){
		array_push($this->category,$categrory);
	}
	public function add_category_by_id($category_id){
		$this->add_category(new Category($categrory_id));
	}
	public function remove_category(Category $category){
		$categories=array();
		foreach($this->category as $this_category){
			if($category != $this_category){
				$categories[]=$this_category;
			}
		}
		$this->category=$categories;
	}
	public function remvoe_category_by_id($category_id){
		$this->remove_category( new Category($categrory_id));
	}
	public function __construct(){
		$args=func_get_args();
		ClassUtil::callMethodForArgs($this,$args);
	}
	public function construct_(){
	}
	public  function construct_Category($category){
		$this->add_category($category);
	}
	
	/*
	id 	int(11) 
	user_id 	int(11)
	category_id 	int(11)

	id 	int(11) 
	content_id 	int(11)
	category_id 	int(11)
	*/
	private function db_save_category($type,$target_id,$category_id){
		//check exsit
		$sql="select id from {$type}_category where {$type}_id='$target_id' and category_id='$category_id'";
		$query = db_query($sql, "users", "read");
		$result=db_get_row_array($query);
		if(!empty($result)) return ;
		//insert value
		$sql="insert into {$type}_category ({$type}_id,category_id) values ('$target_id','$category_id')";
		$query = db_query($sql, "users", "write");
		if(!mysql_insert_id()) throw new LyException("save '$type' category fails");
		return mysql_insert_id();
	}
	public function save_user_category($user_id){
		foreach($this->category as $this_category){
			$this->db_save_category("user",$user_id,$this_category->id);
		}
	}
	public function save_content_category($content_id){
		foreach($this->category as $this_category){
			$this->db_save_category("content",$content_id,$this_category->id);
		}
	}
	public function get_user_category($user_id){
		$this->db_get_category("user",$user_id);
	}
	public function get_content_category($content_id){
		$this->db_get_category("content",$content_id);
	}
	private function db_get_category($type,$target_id){
		$sql="slect category_id from {$type}_category where {$type}_id='$target_id'";
		$query = db_query($sql, "users", "read");
		$result=db_get_row_array($query);
		foreach($result as $category_id){
			$this->add_category_by_id($category_id);
		}
	}
									  
}
?>